package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

@Service
@Slf4j
public class CyclicBarrierExampleService {

    private final CyclicBarrier barrier = new CyclicBarrier(3, () -> log.info("所有线程到达屏障点，继续执行后续操作"));

    public void executeTasksWithBarrier() {
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                log.info("线程 {} 到达屏障点", Thread.currentThread().getName());
                try {
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    Thread.currentThread().interrupt();
                }
            }).start();
        }
    }
}
